package Ex2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Q1 
{	
	public static void main(String[] args) 
	{
		MyGraph g = buildGraph("/Users/itay/Desktop/ex2Input");
		
		g.print();
	}
	
	public static MyGraph buildGraph(String repoPath)
	{
		MyGraph g = new MyGraph();
		
		File filbert = new File(repoPath);
		File[] fileList = filbert.listFiles();
		
		Set<String> links;
		
		for (File file : fileList) 
		{	
			g.addVertex(file.getName());
			
			links = getLinks(file);
			
			for (String href : links) 
			{
				if(!g.isVertexExists(href))
				{
					g.addVertex(href);
				}
				
				g.addEdge(file.getName(), href);
			}
		}
		
		return g;
	}
	
	private static Set<String> getLinks(File file)
	{
		Set<String> links = new LinkedHashSet<String>();
		
		String text = loadTextFromFile(file);

		Pattern patternTag, patternLink;
		Matcher matcherTag, matcherLink;
	
		patternTag = Pattern.compile("(?i)<a([^>]+)>(.+?)</a>");
		patternLink = Pattern.compile("\\s*(?i)href\\s*=\"\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))");
		
		matcherTag = patternTag.matcher(text);

		while (matcherTag.find()) 
		{
			String href = matcherTag.group(1); // href

			matcherLink = patternLink.matcher(href);

			while (matcherLink.find()) 
			{
				String link = matcherLink.group(1); // link
				links.add(link);
			}
		}
		return links;
	}
	
	public static String loadTextFromFile(File file)
	{
		String res = "";
		try 
		{ 
			if (file.exists() == false) 
			{ 
				return res; 
			}
			else 
			{ 
				FileInputStream in = new FileInputStream(file);
				BufferedReader brin = new BufferedReader(new InputStreamReader(in));
				
				while (brin.ready()) 
				{ 
					res += (brin.readLine() + "\n");
				}
				brin.close();
				in.close();
			}
		} 
		catch (Exception ex) 
		{ 
			ex.printStackTrace();
		}
	
		return res;
	}
}
